package com.link.base.base.gateway.service;

import com.link.base.base.user.model.OnlineUser;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.StringUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 网关接口统一调用处
 *
 * @author huanglongjian
 * @date 2019-08-26 19:59
 */

@Service
public class GatewayServiceImpl implements GatewayService {

    private static final String GATEWAY_NAME = "link-gateway";

    @Resource
    private RestTemplate restNoLbTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private Environment env;

    /**
     * 刷新网关中的缓存信息
     *
     * @author huanglongjian
     * @date 2019-08-26 20:01
     */
    @Override
    public void refreshAllCache(String type) throws Exception {

        List<ServiceInstance> instanceList = getGatewayInstance();
        for (ServiceInstance serviceInstance : instanceList) {

            String homeUrl = ((EurekaDiscoveryClient.EurekaServiceInstance) serviceInstance).getInstanceInfo().getHomePageUrl();
            String path = homeUrl + "/gateway/cache/refresh";
            Map<String, Boolean> response = restNoLbTemplate.postForObject(path, type, Map.class);
            if (response == null) {
                throw new Exception("调用gateway接口报错！");
            }
            if (!response.get("success")) {
                throw new Exception(String.valueOf(response.get("result")));
            }
        }
    }


    /**
     * 获取网关的实例
     * 
     * @author huanglongjian
     * @date 2019-08-26 20:10
     */
    private List<ServiceInstance> getGatewayInstance() {
        String gatewayServiceName = env.getProperty("gateway.servicename");
        if (StringUtils.isBlank(gatewayServiceName)) {
            gatewayServiceName = GATEWAY_NAME;
        } else {
            gatewayServiceName = gatewayServiceName.toLowerCase();
        }

        return discoveryClient.getInstances(gatewayServiceName);
    }

    /**
     * 强制用户下线时，将gateway缓存的token删除
     *
     * @author 郭闪
     * @date 2020/1/2
     * @param onlineUser  在线用户实体
     * @param token 内部token，在gateway中校验是否是合法请求
     *
     */
    @Override
    public void invalidateToken(OnlineUser onlineUser,String token) {
        //构造请求参数和请求头
        String reKey = onlineUser.getReKey();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", token);
        headers.add("Content-Type", "application/json");
        HttpEntity<String> entity = new HttpEntity<>(reKey.replace("auth_user_",""), headers);


        //获取服务列表，向每个服务发送更新url的请求
        List<ServiceInstance> instances = this.getGatewayInstance();
        for (ServiceInstance instance : instances) {

            String homeUrl = ((EurekaDiscoveryClient.EurekaServiceInstance) instance).getInstanceInfo().getHomePageUrl();
            String path = homeUrl + "gateway/cache/invalidateToken";

            Map<String, Object> resp = this.restNoLbTemplate.postForObject(path, entity, Map.class);
            if (!(Boolean)resp.get("success")) {
                throw new BasicServiceException(resp.get("result") + "");
            }
        }

    }
}
